--- title: "6、交换瓶子" created: 2025-11-28 tags: - 算法 --- # 6、交换瓶子 ## 题目 [交换瓶子](https://www.lanqiao.cn/paper/3860/problem/126/) ![[image-7611bd61.png]] ## 思路分析 用的上次贪心的结论 最少交换数就是逆序对的数量 然后就直接归并排序模版套上去了 参考:超快速排序 ```cpp #include using namespace std; typedef long long LL; const int N=1e4+10; int a[N]; LL merge_sort(int q[],int l,int r) { if(l>=r) return 0; int mid= l + r >> 1; LL res=merge_sort(q,l,mid) + merge_sort(q,mid+1,r); int k=0,i=l,j=mid+1,tmp[r-l+1]; while(i<=mid && j<=r) { if(q[i]<=q[j]) tmp[k++]=q[i++]; else { tmp[k++]=q[j++]; res+=mid-i+1; } } while(i<=mid) tmp[k++]=q[i++]; while(j<=r) tmp[k++]=q[j++]; for(i=l,k=0;i<=r;i++,k++) q[i]=tmp[k]; return res; } int main() { int n; cin>>n; for(int i=0;i>a[i]; cout< using namespace std; typedef long long LL; const int N=1e4+10; int a[N],ans,n; int main() { cin>>n; for(int i=1;i<=n; i++) scanf("%d", &a[i]); for(int i=1; i<=n; i++) { while(a[i]!=i) { swap(a[i], a[a[i]]); ++ans; } } cout<